package software

import (
	"context"

	"github.com/gogf/gf/v2/frame/g"

	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
	"github.com/influxdata/influxdb-client-go/v2/api"
	"github.com/influxdata/influxdb-client-go/v2/api/write"
)

func NewInfluxDB(ctx context.Context) *InfluxDB {
	endpoint := g.Config().MustGet(ctx, "app.influxdb.endpoint").String()
	token := g.Config().MustGet(ctx, "app.influxdb.token").String()

	return &InfluxDB{
		ctx:    ctx,
		client: influxdb2.NewClient(endpoint, token),
	}
}

type InfluxDB struct {
	ctx    context.Context
	client influxdb2.Client
}

func (r *InfluxDB) Write(org, bucket string, point *write.Point) {
	if err := r.client.WriteAPIBlocking(org, bucket).
		WritePoint(r.ctx, point); err != nil {
		panic(err)
	}
}
func (r *InfluxDB) Query(org, query string) *api.QueryTableResult {
	results, err := r.client.QueryAPI(org).
		Query(r.ctx, query)
	if err != nil {
		panic(err)
	}

	return results
}
